import { UPDATEPAGECITYLOCATION } from '../types/pagecitylocation'
import { createAction } from 'redux-actions'
import {
  getCityListRequest,
  getHistoryListRequest,
  searchCityRequest
} from '../../../../../service/city-controller'

export const DOREQUESTCITYLOCATION = createAction(UPDATEPAGECITYLOCATION, payload => {
  return new Promise(resolve => {
    getCityListRequest().then(({ data }) => {
      let format = (data && data.entry) || []
      resolve({
        cityList: formatCityList(format)
      })
    })
  })
})

export const DOREQUESTRECENTLY = createAction(UPDATEPAGECITYLOCATION, payload => {
  return new Promise(resolve => {
    getHistoryListRequest().then(({ data }) => {
      let format = (data && data.entry) || []
      resolve({
        recentlyList: format
      })
    })
  })
})

const formatCityList = entry => {
  if (!entry) {
    return []
  }
  let returnObj = {}
  entry.forEach(data => {
    if (!returnObj[data.extra]) {
      returnObj[data.extra] = []
    }
    data.name = data.cityName
    returnObj[data.extra].push(data)
  })
  let returnArr = []
  for (let attr in returnObj) {
    returnArr.push({
      title: attr,
      key: attr,
      items: returnObj[attr]
    })
  }
  returnArr = returnArr.sort(
    (a, b) => a.title.toLowerCase().charCodeAt() - b.title.toLowerCase().charCodeAt()
  )
  return returnArr
}

export const DOREQUESTONSEARCH = createAction(UPDATEPAGECITYLOCATION, ({ value }) => {
  return new Promise(resolve => {
    searchCityRequest({ keyWords: value }).then(({ data }) => {
      let format = (data && data.entry) || []
      resolve({
        cityList: formatCityList(format)
      })
    })
  })
})
